<template>
  <div class="detect-container">
    <div class="operation-box">
      <el-steps :active="activeStepIndex" simple>
        <el-step title="步骤 1:选择地块" icon="el-icon-position"></el-step>
        <el-step title="步骤 2:图像上传" icon="el-icon-upload"></el-step>
        <el-step title="步骤 3:检测结果" icon="el-icon-s-flag"></el-step>
      </el-steps>
      <el-divider></el-divider>
      <div class="step-tabs">
        <!--  步骤 1 -->
        <div class="tab-1-zone" v-if="activeStepIndex==0">
          <div class="select-zone-box">
            <span class="select-zone-tip">请选择当前地块：</span>
            <el-select v-model="currentZone" placeholder="请选择">
              <el-option
                  v-for="item in zoneOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </div>
          <a-map :default-value="postForm.detailedAddress" @getPosition="getPosition"/>
        </div>
        <!--  步骤 2 -->
        <div class="tab-2-upload" v-if="activeStepIndex==1">
          <div v-if="!imageUrl" class="img-upload">
            <el-upload ref="upload"
                       name="file"
                       action="/api/common/upload"
                       accept="image/jpg,image/jpeg,image/png"
                       :drag="true"
                       :auto-upload="false"
                       :on-change="onImageChange"
            >
              <!--
                action必选参数，自动上传使用的地址  action="/api/common/upload"
                http-request:覆盖默认的action上传行为  :http-request="doUpload"
                :headers="headers"  请求头在计算属性中
                file-list：上传的文件列表array
                multiple 是否支持多选文件
              -->
              <div>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </div>
              <div class="el-upload__tip" slot="tip">
                <p style="text-align: center">只能上传jpg/jpeg/png文件，且不超过10MB</p>
              </div>
            </el-upload>
          </div>
          <!-- 预览 -->
          <div v-else class="img-preview">
            <el-image :src="imageUrl" :preview-src-list="[imageUrl]" fit="scale-down"></el-image>
          </div>
        </div>
        <!--  步骤 3 -->
        <div class="tab-3-result" v-if="activeStepIndex==2">
          <div class="result-box">
            <div class="result-table">
              <el-descriptions title="检测结果"
                               :column="1"
                               border
                               :contentStyle= "{'min-width':'150px'}"
                               :label-style = "{'min-width':'150px'}"
              >
                <el-descriptions-item label="果蔬名称">{{ result.fruitName }}</el-descriptions-item>
                <el-descriptions-item label="成熟数量">{{ result.matureCount }}</el-descriptions-item>
                <el-descriptions-item label="果实总数量">{{ result.totalCount }}</el-descriptions-item>
                <el-descriptions-item label="成熟率">
                  {{ result.matureCount / result.totalCount * 100}}%
                </el-descriptions-item>
              </el-descriptions>
              <el-button type="success" @click="doNewStep" v-if="activeStepIndex==2">
                <i class="el-icon-finished"></i>&nbsp;完成
              </el-button>
            </div>
            <div>
              <img :src="imageUrl">
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="botton-box">
      <el-button type="primary" @click="doSecondStep"
                 v-if="activeStepIndex==0">
        下一步&nbsp;<i class="el-icon-arrow-right"></i>
      </el-button>
      <el-button type="primary" @click="doFirstStep"
                 v-if="activeStepIndex==1">
        <i class="el-icon-arrow-left"></i>&nbsp;返回
      </el-button>
      <el-button type="danger" @click="redoUpload"
                 v-if="activeStepIndex==1 && imageUrl">
        <i class="el-icon-refresh-left"></i>&nbsp;重新选图
      </el-button>
      <el-button type="warning" @click="doDetect" :loading="detectLoading"
                 v-if="activeStepIndex==1 && imageUrl">
        {{detectBtnText}}
      </el-button>
    </div>


  </div>
</template>

<script>

import aMap from "@/components/AMap";
import {detectImage, uploadImage} from "@/api/detect";
import {addHistory} from "@/api/history";

export default {
  name: "imageUpload",
  components: {
    aMap
  },
  data() {
    return {
      //当前激活的步骤
      activeStepIndex: 0,
      // 上传图片的表单
      formData: {
        file: null
      },
      //当前地块
      currentZone:'',
      //上传图片的访问路径
      imageUrl: '',
      isShowPreview: false,
      isShowUpload: true,
      //检测结果
      result: {
        fruitName: '',
        varietyCode:'',
        matureCount: 0,
        totalCount: 0,
        imgBase64: null
      },
      //地块的选项
      zoneOptions: [{
        value: '选项1',
        label: '黄金糕'
      }, {
        value: '选项2',
        label: '双皮奶'
      }, {
        value: '选项3',
        label: '蚵仔煎'
      }],
      //检测按钮的loading状态
      detectLoading:false,
      detectBtnText:'提交',
      //  地图
      postForm: {
        detailedAddress: '',
        longitude: '',
        latitude: ''
      }
    }
  },
  methods: {
    onImageChange(file) {
      // 图片格式校验
      if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 10
        if (['png', 'jpeg', 'jpg', 'PNG', 'JPEG', 'JPG'].indexOf(suffix) < 0) {
          this.$message.error('上传失败！图片只支持 png、jpeg、jpg 格式！')
          this.$refs.upload.clearFiles()
          return false
        }
        if (!size) {
          this.$message.error('上传文件大小不能超过 10MB!')
          this.$refs.upload.clearFiles()
          return false
        }
      }
      // 本地预览
      // 获取上传图片的本地URL，用于上传前的本地预览
      var URL = null;
      if (window.createObjectURL != undefined) {
        // basic
        URL = window.createObjectURL(file.raw);
      } else if (window.URL != undefined) {
        // mozilla(firefox)
        URL = window.URL.createObjectURL(file.raw);
      } else if (window.webkitURL != undefined) {
        // webkit or chrome
        URL = window.webkitURL.createObjectURL(file.raw);
      }
      // 本地转换后的地址进行赋值
      this.imageUrl = URL;
      this.isShowPreview = true; //呈现本地预览组件
      this.isShowUpload = false;   //隐藏上传组件
      //准备表单数据
      this.formData.file = file.raw
    },
    doDetect() {
      this.detectLoading = true;
      this.detectBtnText = '正在检测...';
      const loader = this.$loading({
        lock: true,
        text: '正在进行检测，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.6)'
      });
      //真正上传到服务器
      uploadImage(this.formData).then(res => {
        const {data} = res
        if (data.code === 200) {
          this.$message({
            message: '图片上传成功',
            type: 'success'
          })
          //请求检测
          const filename = data.data;
          detectImage({filename: filename}).then(res2 => {
            const {data} = res2
            // console.log(data)
            if (data.code === 200) {
              //返回成功的检测结果
              this.result.fruitName = data.data.info[0].FruitName;
              this.result.matureCount = data.data.info[0].MatureCount;
              this.result.totalCount = data.data.info[0].TotalCount;
              this.result.imgBase64 = data.data.image
              //国蔬品种识别码
              this.result.varietyCode = this.result.fruitName
              this.detectLoading = false;
              this.detectBtnText = '提交';
              //关闭loading
              loader.close();
              this.showFinishStep();
            }else{
              this.$message({
                message: '检测失败',
                type: 'error'
              })
              loader.close();
              this.detectLoading = false;
              this.detectBtnText = '提交';
            }
          }).catch(err=>{
            this.$message({
              message: '响应超时，检测失败',
              type: 'error'
            })
            loader.close();
            this.detectLoading = false;
            this.detectBtnText = '提交';
          })
        }

      })
    },
    addToHistory(){
      //将检测结果添加到历史
      if(this.result){
        addHistory(this.result).then(res=>{
          const {data} = res
          if (data.code === 200) {
            this.$message({
              message: data.msg,
              type: 'success'
            })
          }else{
            this.$message({
              message: data.msg,
              type: 'error'
            })
          }
        })
      }

    },
    doFirstStep() {
      this.activeStepIndex = this.activeStepIndex - 1
    },
    doSecondStep() {
      this.activeStepIndex = this.activeStepIndex + 1
    },
    redoUpload() {
      this.imageUrl = ''
      this.isShowUpload = true
      this.isShowPreview = false
    },
    showFinishStep() {
      this.activeStepIndex = 2;
      this.imageUrl = "data:image/*;base64," + this.result.imgBase64;
    },
    doNewStep() {
      //保存到历史
      this.addToHistory();
      this.activeStepIndex = 0;
      this.imageUrl = "";
    },
    //获取当前的地理位置
    getPosition({ address, lat, lng, name }) {
      this.postForm.detailedAddress = address;
      this.postForm.longitude = String(lng);
      this.postForm.latitude = String(lat);
    }
  },
  computed: {}
}
</script>

<style scoped lang="less">
.detect-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;

  .operation-box {
    //使用剩余的全部空间
    flex: 1;
    display: flex;
    flex-direction: column;

    .step-tabs {
      flex: 1;
      display: flex;
      justify-content: center;

      .tab-1-zone {
        width: 60%;

        .select-zone-box {
          padding: 10px 0px;

          .select-zone-tip {
            font-size: 16px;
          }
        }
      }

      .tab-2-upload {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;

        .img-upload {
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .img-preview {
          justify-content: center;

          .el-image {
            width: 100%;
            height: 60vh; //预览图显示高度
          }
        }
      }

      .tab-3-result {
        width: 80%;
        .result-box {
          display: flex;
          justify-content: space-evenly;
          align-items: center;
          .result-table{
            display: flex;
            flex-direction: column;
            align-items: center;
            .el-descriptions{
              margin-bottom: 50px;
            }
          }
        }
      }
    }
  }

  .botton-box {
    height: 90px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

img {
  width: 500px;
  height: 500px;
}
</style>
